package cn.lblbc.webbrowser.utils

import android.content.Context
import android.webkit.WebView
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.net.HttpURLConnection
import java.net.URL
import java.util.UUID

data class ImageInfo(val url: String, val width: Int, val height: Int)

class ImageCollector(private val context: Context) {
    
    private val settings = ImageCollectionSettings(context)
    
    private val imageDirectory: File by lazy {
        File(context.getExternalFilesDir(null), "Pictures/WebImages").apply {
            if (!exists()) {
                mkdirs()
            }
        }
    }
    
    /**
     * 从WebView中收集图片
     */
    fun startCollecting(webView: WebView) {
        // 检查是否启用图片收集
        if (!settings.isEnabled) {
            return
        }
        
        try {
            // 注入JavaScript来获取页面中的所有图片URL和尺寸
            val javascript = """
                (function() {
                    var images = [];
                    var imgElements = document.getElementsByTagName('img');
                    for (var i = 0; i < imgElements.length; i++) {
                        var img = imgElements[i];
                        if (img.src && img.src.startsWith('http')) {
                            // 检查图片尺寸，根据设置过滤
                            if (img.naturalWidth >= ${settings.minWidth} && img.naturalHeight >= ${settings.minHeight}) {
                                images.push({
                                    url: img.src,
                                    width: img.naturalWidth,
                                    height: img.naturalHeight
                                });
                            }
                        }
                    }
                    return images;
                })();
            """.trimIndent()
            
            webView.evaluateJavascript(javascript) { result ->
                try {
                    // 解析JavaScript返回的结果
                    if (result != null && result != "null" && result.startsWith("[")) {
                        val imageData = parseImageData(result)
                        if (imageData.isNotEmpty()) {
                            downloadImages(imageData)
                        }
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    
    /**
     * 解析JavaScript返回的图片数据数组
     */
    private fun parseImageData(jsonResult: String): List<ImageInfo> {
        try {
            val imageList = mutableListOf<ImageInfo>()
            val cleanResult = jsonResult.trim().removeSurrounding("[", "]")
            
            if (cleanResult.isNotEmpty()) {
                // 简单解析JSON对象数组
                val objectPattern = Regex("""\{[^}]+\}""")
                val matches = objectPattern.findAll(cleanResult)
                
                for (match in matches) {
                    val objStr = match.value
                    val urlMatch = Regex(""""url":"([^"]+)"""").find(objStr)
                    val widthMatch = Regex(""""width":(\d+)""").find(objStr)
                    val heightMatch = Regex(""""height":(\d+)""").find(objStr)
                    
                    if (urlMatch != null && widthMatch != null && heightMatch != null) {
                        val url = urlMatch.groupValues[1]
                        val width = widthMatch.groupValues[1].toInt()
                        val height = heightMatch.groupValues[1].toInt()
                        
                        // 再次检查尺寸是否符合要求
                        if (settings.shouldCollectImage(width, height)) {
                            imageList.add(ImageInfo(url, width, height))
                        }
                    }
                }
            }
            
            return imageList
        } catch (e: Exception) {
            e.printStackTrace()
            return emptyList()
        }
    }
    
    /**
     * 下载图片列表
     */
    private fun downloadImages(imageData: List<ImageInfo>) {
        CoroutineScope(Dispatchers.IO).launch {
            for (imageInfo in imageData.take(10)) { // 限制最多下载10张图片
                try {
                    downloadSingleImage(imageInfo.url)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }
    
    /**
     * 下载单张图片
     */
    private suspend fun downloadSingleImage(imageUrl: String) {
        withContext(Dispatchers.IO) {
            try {
                val url = URL(imageUrl)
                val connection = url.openConnection() as HttpURLConnection
                connection.connectTimeout = 10000
                connection.readTimeout = 15000
                connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Linux; Android 10) AppleWebKit/537.36")
                
                connection.connect()
                
                if (connection.responseCode == HttpURLConnection.HTTP_OK) {
                    val inputStream = connection.inputStream
                    
                    // 生成唯一的文件名
                    val fileExtension = getFileExtension(imageUrl, connection.contentType)
                    val fileName = "${UUID.randomUUID()}.$fileExtension"
                    val imageFile = File(imageDirectory, fileName)
                    
                    // 检查文件是否已存在（避免重复下载）
                    if (!imageFile.exists()) {
                        val outputStream = FileOutputStream(imageFile)
                        
                        inputStream.use { input ->
                            outputStream.use { output ->
                                input.copyTo(output)
                            }
                        }
                        
                        println("图片已保存: ${imageFile.absolutePath}")
                    }
                }
                
                connection.disconnect()
                
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
    
    /**
     * 获取文件扩展名
     */
    private fun getFileExtension(url: String, contentType: String?): String {
        return when {
            contentType?.contains("jpeg") == true || contentType?.contains("jpg") == true -> "jpg"
            contentType?.contains("png") == true -> "png"
            contentType?.contains("gif") == true -> "gif"
            contentType?.contains("webp") == true -> "webp"
            url.contains(".jpg", ignoreCase = true) -> "jpg"
            url.contains(".jpeg", ignoreCase = true) -> "jpg"
            url.contains(".png", ignoreCase = true) -> "png"
            url.contains(".gif", ignoreCase = true) -> "gif"
            url.contains(".webp", ignoreCase = true) -> "webp"
            else -> "jpg" // 默认使用jpg
        }
    }
    
    /**
     * 获取已图库列表
     */
    fun getCollectedImages(): List<File> {
        return try {
            if (imageDirectory.exists()) {
                imageDirectory.listFiles { file ->
                    file.isFile && file.extension.lowercase() in listOf("jpg", "jpeg", "png", "gif", "webp")
                }?.sortedByDescending { it.lastModified() }?.toList() ?: emptyList()
            } else {
                emptyList()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            emptyList()
        }
    }
    
    /**
     * 获取已图库数量
     */
    fun getCollectedImageCount(): Int {
        return try {
            if (imageDirectory.exists()) {
                imageDirectory.listFiles { file ->
                    file.isFile && file.extension.lowercase() in listOf("jpg", "jpeg", "png", "gif", "webp")
                }?.size ?: 0
            } else {
                0
            }
        } catch (e: Exception) {
            0
        }
    }
    
    /**
     * 获取图片存储目录
     */
    fun getImagesDirectory(): File = imageDirectory
    
    /**
     * 清除所有图库
     */
    fun clearAllImages(): Int {
        return try {
            var deletedCount = 0
            if (imageDirectory.exists()) {
                val imageFiles = imageDirectory.listFiles { file ->
                    file.isFile && file.extension.lowercase() in listOf("jpg", "jpeg", "png", "gif", "webp")
                }
                
                imageFiles?.forEach { file ->
                    if (file.delete()) {
                        deletedCount++
                    }
                }
            }
            deletedCount
        } catch (e: Exception) {
            0
        }
    }
}